/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
 * MA  02110-1301, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */
package system.database.mysql5;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import javolution.util.FastMap;

import org.apache.log4j.Logger;

import com.aionemu.commons.database.DB;
import com.aionemu.loginserver.dao.AccountCharactersDAO;

/**
 * @author lyahim
 *
 */
public class MySQL5AccountCharactersDAO extends AccountCharactersDAO
{
	private static final Logger	log	= Logger.getLogger(MySQL5AccountCharactersDAO.class);

	@Override
	public boolean supports(String databaseName, int majorVersion, int minorVersion)
	{
		return MySQL5DAOUtils.supports(databaseName, majorVersion, minorVersion);
	}

	@Override
	public Map<Byte, Integer> getCharacterCountByAccountId(int accountId)
	{
		String query = "SELECT * FROM account_characters WHERE account_id=?";
		final Map<Byte, Integer> result = new FastMap<Byte, Integer>();
		PreparedStatement st = DB.prepareStatement(query);
		try
		{
			st.setInt(1, accountId);
			ResultSet resultSet = st.executeQuery();
			while (resultSet.next())
			{
				byte id = resultSet.getByte("gameserver_id");
				int count = resultSet.getInt("player_count");
				result.put(id, count);
			}
		}
		catch (SQLException e)
		{
			log.error("Error in select query");
		}
		finally
		{
			DB.close(st);
		}
		return result;
	}

	@Override
	public void setCharacterCount(int accountId, Byte gameserverId, int value)
	{
		String query1 = "UPDATE account_characters SET `player_count` = ? WHERE `gameserver_id` = ? AND `account_id` = ?";
		String query2 = "INSERT INTO account_characters(player_count, gameserver_id, account_id) VALUES (?,?,?)";
		Map<Byte, Integer> chars = getCharacterCountByAccountId(accountId);
		PreparedStatement st = null;
		if (chars.get(gameserverId) != null)
			st = DB.prepareStatement(query1);
		else
			st = DB.prepareStatement(query2);
		try
		{
			st.setInt(1, value);
			st.setInt(2, gameserverId);
			st.setInt(3, accountId);
			st.executeUpdate();
		}
		catch (SQLException e)
		{
			log.error("Error in update query");
			log.error(e);
		}
		finally
		{
			DB.close(st);
		}
	}
}
